const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const fs = require('fs');

// 配置multer存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, path.join(__dirname, '../static'));
  },
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    cb(null, uuidv4() + ext);
  }
});

const upload = multer({ storage });

// 文件上传
router.post('/upload', upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({
        code: 400,
        message: '未上传文件'
      });
    }

    // 对原始文件名进行编码处理
    const originalName = Buffer.from(req.file.originalname, 'latin1').toString('utf8');

    res.json({
      code: 200,
      data: {
        originalName: originalName,  // 使用处理后的文件名
        fileName: req.file.filename,
        filePath: `/static/${req.file.filename}`
      },
      message: '上传成功'
    });
  } catch (err) {
    res.status(500).json({
      code: 500,
      message: err.message
    });
  }
});

// 清空Neo4j数据库
router.post('/clear-neo4j', async (req, res) => {
    // 验证请求中的密钥，避免未授权访问
    const { secretKey } = req.body;
    if (secretKey !== 'admin123') { // 设置一个密钥，实际应用中应使用更安全的认证方式
        return res.send({ code: 403, message: '未授权的操作' });
    }
    const session = req.neo4j.session();
    try {
        // 删除所有关系
        await session.run(`MATCH ()-[r]-() DELETE r`);
        
        // 删除所有节点（除了User节点，保留用户数据）
        await session.run(`MATCH (n) WHERE NOT n:User DELETE n`);
        
        // 可选：如果也想删除User节点，取消下面的注释
        // await session.run(`MATCH (n:User) DELETE n`);
        
        res.send({ 
            code: 200, 
            message: 'Neo4j数据库已成功清空'
        });
    } catch (error) {
        console.error('清空Neo4j数据库失败:', error);
        res.send({
            code: 500,
            message: `清空失败: ${error.message}`
        });
    } finally {
        await session.close();
    }
});

module.exports = router;
